from Config import *
from Logger import *
from Server import *
#from MessageHandler import *


class Pinger:
    
    def __init__(self, handler, log, mSender, server):
        self.pinger = Thread(target = self.loop)
        self.mHandler = handler
        self.log = log
        self.mSender = mSender
        self.server = server
        
    # voor de Thread
    def loop(self):
        log.add_queue("Ping thread started")
        while True:
            # pseudocode
            # waar moet het IP adres en de poort van "deze" server opgeslagen worden?
            # get all servers/nodes from the tree
            # if no connection for 32 seconds
                # disconnect
            # else
                # send ping message
            
            for child in server.children:
                # TODO: hoe kan je erachter komen 1. is server parent?
                # 2. hoe lang geleden reageerde de server voor het laats?
                if (time.time() - server.last_reacted > 32):
                    msg = "Server "+child.address+" 32 seconds inactive."\
                    "Sending ping " 
                    log.add_queue(msg, "Pinger")
                    msg = mHandler.create_message(140, 1, server.tag)
                    mSender.add_queue(msg, child.address)
                    time.sleep(2)
                    if(time.time() - server.last_reacted > 2):
                        server.remove(server)
                        msg = mHandler.create_message(603, "Server "+server.address+" removed.")
                        mSender.add_queue(msg, CONTROL_SERVER_ADDRESS)
                        
            for client in self.server.clients:
                if (time.time() - client.last_reacted > 32):
                    msg = "Server "+child.address+" 32 seconds inactive."\
                    "Sending ping " 
                    log.add_queue(msg, "Pinger")
                    msg = mHandler.create_message(140, 1, server.tag)
                    mSender.add_queue(msg, child.address)
                    time.sleep(2)
                    if(time.time() - child.last_reacted > 2):
                        server.clients.remove(client)
                        msg = mHandler.create_message(130, 1, client.name)
                        mSender.add_queue(msg, client.address)
                        

        time.sleep(0.5)
        log.add_queue("Ping thread exited", "Pinger")


      